package com.lujieni.springbootwebsocket.server;
 
import com.alibaba.fastjson.JSON;
import com.lujieni.springbootwebsocket.dao.WebsiteMsgDao;
import com.lujieni.springbootwebsocket.po.WebsiteMsgPO;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.common.Mapper;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 *
 * 它不是单例 不是单例!!!
 */
@Component
@ServerEndpoint("/websocket/{userCode}")
public class WebSocketServer implements ApplicationContextAware {
 
    // 保存所有的客户端连接
    private static final Map<String, Session> connections = new ConcurrentHashMap<>();

    private String userCode;

    private static ApplicationContext applicationContext;
 
    @OnOpen
    public void onOpen(Session session, @PathParam("userCode") String userCode) throws ClassNotFoundException, IOException {
        this.userCode = userCode;
        connections.put(userCode, session);
        Mapper<WebsiteMsgPO> mapper = applicationContext.getBean(WebsiteMsgDao.class);
        WebsiteMsgPO record = new WebsiteMsgPO();
        record.setUserCode(userCode);
        List<WebsiteMsgPO> list = mapper.select(record);
        sendMessageToSpecificClient(JSON.toJSONString(list), session);
    }
 
    @OnMessage
    public void onMessage(String message) {
        try {
            System.out.println("收到客户端:"+userCode+"的消息,消息为:"+message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @OnError
    public void onError(Throwable error, Session session) throws Throwable {
        throw error;
    }
 
    @OnClose
    public void onClose() {
        System.out.println("关闭连接");
        connections.remove(userCode);
    }

    public WebSocketServer(){
        System.out.println("WebSocketServer");
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendMessageToSpecificClient(String message, Session session) throws IOException {
        if(session != null) {
            session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 校验是否在线,在线需要返回用户session信息
     */
    public static Session checkIsOnline(String login) throws IOException {
        for (String onLineLogin : connections.keySet()) {
            if(login.equals(onLineLogin)){
                return connections.get(login);
            }
        }
        return null;
    }

    // 广播方法(实现消息群发)
    public static void broadcast(String message) {
        connections.forEach((k, v) -> {
            try {
                v.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}